import datetime, hashlib, uuid, time
from operator import index
from homeassistant.components.http import HomeAssistantView
from homeassistant.helpers.network import get_url
from homeassistant.helpers.storage import STORAGE_DIR

from .const import DOMAIN_API, DOMAIN
from .shaonianzhentan import save_yaml, load_yaml

CONFIG_FILE = f'{STORAGE_DIR}/homepage.yaml'

class View(HomeAssistantView):
    url = DOMAIN_API
    name = DOMAIN
    requires_auth = True

    def save_config(self, hass, data):
        save_yaml(hass.config.path(CONFIG_FILE), data)

    def datetime_now(self):
        return datetime.datetime.now().replace(microsecond=0).isoformat()

    def md5(self, text):
        return hashlib.md5(text.encode(encoding='UTF-8')).hexdigest()

    async def post(self, request):
        response = await request.json()
        hass = request.app["hass"]
        type = response.get('type', '')
        data = response.get('data')
        if type == 'site':
            # 查看所有数据
            config = load_yaml(CONFIG_FILE)
            arr = config.get('site', [])
            _type = data.get('_type')
            if _type == 'add':
                arr.append({
                    'count': 0,
                    'createdTime': self.datetime_now(),
                    'updatedTime': self.datetime_now(),
                    'iconUrl': data.get('iconUrl'),
                    'name': data.get('name'),
                    'url': data.get('url'),
                    '_id': str(int(time.time()))
                })
                # 保存数据
                config['site'] = arr
                self.save_config(hass, config)
            elif _type == 'del':
                id = data.get('id')
                for item in arr:
                    if item['_id'] == id:
                        arr.remove(item)
                        break
                # 保存数据
                config['site'] = arr
                self.save_config(hass, config)
            elif _type == 'set':
                id = data.get('id')
                for index, item in enumerate(arr):
                    if item['_id'] == id:
                        arr[index]['updatedTime'] = self.datetime_now()
                        arr[index]['iconUrl'] = data.get('iconUrl')
                        arr[index]['name'] = data.get('name')
                        arr[index]['url'] = data.get('url')
                        break
                # 保存数据
                config['site'] = arr
                self.save_config(hass, config)

            elif _type == 'count':
                id = data.get('id')
                for index, item in enumerate(arr):
                    if item['_id'] == id:
                        arr[index]['count'] = arr[index]['count'] + 1
                        break
                # 保存数据
                config['site'] = arr
                self.save_config(hass, config)
                
            return self.json(arr)
            
        return self.json({ 'code': 0, 'msg': 'success'})
